package com.shycloud.mido.member.test;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.shycloud.mido.common.util.DBUtil;
import com.shycloud.mido.homework.api.entity.MidoHomeworkMain;
import com.shycloud.mido.homework.sharding.ConsistentHashSharding;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Xiaoxing Yu
 * @date 2020/11/23 下午6:17
 **/
public class TransferThread extends Thread {

	private int startIdx;

	private int step;

	private AtomicInteger atomicInteger;

	private CountDownLatch latch;

	private ConcurrentHashSet<String> sqlSet;

	private Boolean isBatch;

	private Long id;

	public TransferThread() {
	}

	public TransferThread(int startIdx, int step, AtomicInteger atomicInteger,
						  CountDownLatch latch, ConcurrentHashSet<String> sqlSet, Boolean isBatch, Long id) {
		this.startIdx = startIdx;
		this.step = step;
		this.atomicInteger = atomicInteger;
		this.latch = latch;
		this.sqlSet = sqlSet;
		this.isBatch = isBatch;
		this.id = id;
	}

	@Override
	public void run() {
		ConsistentHashSharding consistentHash = new ConsistentHashSharding();
		System.out.println("[Thread-" + Thread.currentThread().getId() + "]: startIdx =" + startIdx + ", count =" + step);
		scanAndDealWithRecords(startIdx, step, Thread.currentThread().getId(), consistentHash, isBatch, id);
		latch.countDown();
	}

	public void scanAndDealWithRecords(int startIdx, int count, long threadId,
									   ConsistentHashSharding consistentHash, Boolean isBatch, Long id) {
		List<MidoHomeworkMain> homeworkList = new ArrayList<MidoHomeworkMain>();

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			conn = DBUtil.getConn("mido_new_homework");
			String sql = isBatch ? "select * from mido_homework_main mhm order by mhm.id ASC limit " + startIdx + "," + count
									: "select * from mido_homework_main mhm where id = " + id;
//			System.out.println(sql);

			pstmt = DBUtil.getPStmt(conn, sql);
			rs = pstmt.executeQuery();

			Collection collection = DBUtil.get(rs, MidoHomeworkMain.class);
			System.out.println(Thread.currentThread().getName() + "-total-" + collection.size());

			for (Iterator it = collection.iterator(); it.hasNext();) {
				MidoHomeworkMain homeworkEntity = (MidoHomeworkMain) it.next();
				homeworkEntity.setTransferTime(new Date());
				homeworkEntity.setIsTransferData("1");

//				System.out.print(homeworkEntity.getId()+ ", ");

//				Integer tableIdx = consistentHash.getInstance().get(
//						homeworkEntity.getTeacherId() + homeworkEntity.getStudentId()) % 4;
//				String sql2 = "select * from mido_homework_main" + tableIdx + " mhm where mhm.id = '"+ homeworkEntity.getId() +"'";
//
//				ResultSet rs2 = DBUtil.getPStmt(conn, sql).executeQuery();
//				Collection collection2 = DBUtil.get(rs2, MidoHomeworkMain.class);
//				for (Iterator it = collection.iterator(); it.hasNext();) {
//
//				}

				boolean insertResult = insert(homeworkEntity, conn, consistentHash);

//				System.out.println("[Thread-" + threadId + "]Processing transfer with id: "
//						+ homeworkEntity.getId() + ", insert result: "
//						+ insertResult);
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("error occured!");
		} finally {
			DBUtil.closeStmt(pstmt);
			DBUtil.closeConn(conn);
		}
	}

	private boolean insert(MidoHomeworkMain entity, Connection conn, ConsistentHashSharding consistentHash) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String id = null;

		try {
			Integer tableIdx = consistentHash.getInstance().get(
					entity.getTeacherId() + entity.getStudentId()) % 4;
//			System.out.println("tableIdx: " + tableIdx);

			String tableName = "mido_homework_main" + tableIdx;

			String sql = DBUtil.getInsertSql(tableName, MidoHomeworkMain.class, entity);
//			System.out.println("insert sql: " + sql);

			pstmt = DBUtil.getPStmt(conn, sql);

			int result = pstmt.executeUpdate();	//Insert,Update,delete

			sqlSet.add(sql);

			return result == 1 ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeStmt(pstmt);
//			DBUtil.closeConn(conn);
		}

		return false;
	}

	private boolean insertTest(MidoHomeworkMain entity) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String id = null;

		try {
			conn = DBUtil.getConn("192.168.0.184","mido_new_homework");

			String sql = DBUtil.getInsertSql("mido_homework_main0", MidoHomeworkMain.class, entity);
			pstmt = DBUtil.getPStmt(conn, sql);
			int result = pstmt.executeUpdate();	//Insert, Update

			if (result == 0) return false;

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeStmt(pstmt);
			DBUtil.closeConn(conn);
		}

		return false;
	}

}
